<?php

namespace App\Service;

use App\Models\EwAdsPos;

class AdsPosService extends BaseService
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	public static function getList($params, $count = FALSE)
	{
		$query = EwAdsPos::query();
		$query->columns(['DISTINCT(id) AS id,name,is_display,is_del']);
		$query->andWhere("is_del = " . self::DEL_FALSE);

		//is_display
		if (isset($params->is_display) && $params->is_display )
			$query->andwhere("is_display =" . $params->is_display);

		//name
		if (isset($params->name) && $params->name )
			$query->andwhere("name LIKE '%" . $params->name . "%'");

		//总条数
		if ($count)
			return $query->execute()->count();

		//order_by 排序
		if (isset($params->order_by)){
			$sql = parent::orderBy($params->order_by);
			$query->orderBy($sql);
		}

		//分页
		$query->limit($params->page_num,($params->p-1)*$params->page_num);

		return $query->execute();
	}

	public static function getInfo($id = 0)
	{
		return EwAdsPos::findFirst($id);
	}

	public static function count()
	{
		return EwAdsPos::count();
	}

	/**
	 * [display 上架]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function display($id)
	{
		if (isset($id) && $id)
			$data = EwAdsPos::findFirst($id);

		if ($data){
			$data->is_display = $data->is_display ? self::DISPLAY_FALSE : self::DISPLAY_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwAdsPos::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;		
	}

	/**
	 * [delete 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwAdsPos::findFirst($id);

		if ($row)
			return $row->delete();

		return NULL;
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$row = new EwAdsPos;
		if (isset($data->id) && $data->id)
			$row = EwAdsPos::findFirst($data->id);

		return $row->save((array)$data);
	}
}